package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

type Loggers struct {
	Id       int64     `orm:"pk;auto"` // 项目ID
	SpuId    int64     `orm:"size(11)"`
	Title    string    `orm:"size(255)"` // 日志标题
	Module   string    `orm:"size(255)"` // 项目标题模块
	Action   string    `orm:"size(255)"` //行为
	Describe string    `orm:"size(255)"` //描述
	Version  string    `orm:"size(255)"` //版本
	LogTime  time.Time `orm:"auto_now_add;type(datetime)"form:"-"`
	Auther   string    `orm:"size(20)"` //更新者姓名
}

// 获取模型名称
// 获取模型表名
func (m *Loggers) TableName() string {
	return "loggers"
}

// 查询方法
func (m *Loggers) Query() orm.QuerySeter {
	return orm.NewOrm().QueryTable(m)
}

// 添加用户
func (m *Loggers) Insert() error {
	_, err := orm.NewOrm().Insert(m)
	return err
}

// 删除用户
func (m *Loggers) Delete() error {
	_, err := orm.NewOrm().Delete(m)
	return err
}

// 修改用户信息
func (m *Loggers) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(m, fields...)
	return err
}

func (m *Loggers) GetObjectById(id int64) (*Loggers, error) {
	err := m.Query().Filter("id", id).One(m)
	return m, err
}

// log插入操作
func InserSceneLoggerInfo(scene *Scene, userInfo User, action string, desccribe string) {
	logMod := Loggers{}
	logMod.SpuId = scene.Id
	logMod.Version = scene.Version
	logMod.Title = "场景名称:‘" + scene.Title + "’"
	logMod.Action = action
	logMod.Module = "scene"
	logMod.Auther = userInfo.Name
	logMod.Describe = desccribe
	_ = logMod.Insert()
}
func InserProjectLoggerInfo(project *Project, userInfo User, action string, desccribe string) {
	logMod := Loggers{}
	logMod.SpuId = project.Id
	logMod.Title = "项目名称: ‘" + project.Title + "’ "
	logMod.Version = ""
	logMod.Action = action
	logMod.Module = "project"
	logMod.Auther = userInfo.Name
	logMod.Describe = desccribe
	_ = logMod.Insert()
}

func InserUserLoggerInfo(userInfo User, action string, desccribe string) {
	logMod := Loggers{}
	logMod.SpuId = userInfo.Id
	logMod.Title = ""
	logMod.Version = ""
	logMod.Action = action
	logMod.Module = "user"
	logMod.Auther = userInfo.Name
	logMod.Describe = desccribe
	_ = logMod.Insert()
}

func (m *Loggers) GetLoggerByModuleName(module string, sid int64) ([]map[string]interface{}, error) {
	list := make([]*Loggers, 0)
	_, errs := m.Query().Filter("module", module).Filter("spu_id", sid).All(&list)
	resTree := make([]map[string]interface{}, 0)
	for _, citem := range list {
		cres := LoggersJson(citem)
		resTree = append(resTree, cres)
	}
	return resTree, errs
}
